// lock.js
class Lock {
  static _locked = false;
  static _waiting = [];

  static async acquire() {
    if (Lock._locked) {
      await new Promise(resolve => Lock._waiting.push(resolve));
    }
    Lock._locked = true;
  }

  static release() {
    if (Lock._waiting.length > 0) {
      // 有人在等，唤醒下一个
      const next = Lock._waiting.shift();
      next();
    } else {
      Lock._locked = false;
    }
  }

  static async runExclusive(fn) {
    await Lock.acquire();
    try {
      return await fn();
    } finally {
      Lock.release();
    }
  }
}

export default Lock;
